<script setup>
import addForm from "./addForm.vue";
import { onMounted, reactive, ref } from "vue";
import { Share } from "@element-plus/icons-vue";
import { delActivityInfoApi, getActivityListApi } from "../../../api/active";
import Table from "../../../components/Table/table";
import { activeTable } from "@/hooks/activity";
import Pagination from "@/components/Pagination/Pagination";
import ImagePreview from "@/components/ImagePreview";
import { useCommunityNameList } from "@/hooks/index";
import { useActivityStatus } from "@/hooks/index";
import { ElMessage } from "element-plus";
import { formatTimes } from "../../../utils/Fw-data";
import useUserStore from "@/store/modules/user";
import * as XLSX from 'xlsx';


const btnList = useUserStore().btnList
const addRef = ref();
const list = ref([]);
const total = ref(0);
const statusText = useActivityStatus();
const getCommunityNameList = useCommunityNameList();
// const getActivityStatus = useActivityStatus();
const queryData = reactive({
  pageSize: 10,
  current: 1,
  community_code: "",
  title: "",
  status: "",
  create_time: "", //创建时间
  // begin_time: "", //开始时间
  // end_time: "", //结束时间
});

onMounted(() => {
  console.log(btnList);
  initData();
});

// 按钮权限方法
const checkBtnAuth = (id) => {
  if (btnList.length === 0) {
    return true
  } else {
    const ids = btnList.map(item => item.id)

    if (ids.includes(id)) {
      return false
    } else {
      return true
    }
  }
}




// 表格渲染
const initData = async () => {
  const {
    data: { count, rows },
  } = await getActivityListApi(queryData);
  list.value = rows.map(({ photo, ...item }) => ({
    photo:
      import.meta.env.VITE_APP_BASE_IMG +
      (photo ? photo.split(",")[0] : "/public/dist/static/empty.1e2fbc24.png"),
    ...item,
  }));
  // list.value = rows;
  total.value = count;
};

// 处理状态文字
const getStatusText = (val) => {
  let res = statusText.find((item) => item.value === val * 1);
  // console.log(res);
  return res ? res.label : "无效";
};

// 处理时间
const timeArr = ref([]);
watch(timeArr, (val) => {
  console.log(timeArr.value);
  if (timeArr.value) {
    queryData.create_time = val
      .map((item) => {
        item = +new Date(item);
        return item;
      })
      .join(",");
    console.log(queryData.create_time);
  } else {
    queryData.create_time = "";
  }
});
// 搜索
const onSearch = () => {
  queryData.current = 1;
  initData();
  console.log(statusText);
};
// 搜索取消
const onReset = () => {
  Object.assign(queryData, {
    pageSize: 10,
    current: 1,
    community_code: "",
    title: "",
    status: "",
    create_time: "",
  });
  timeArr.value = [];
  initData();
};

// 修改回显
const edit = (id) => {
  addRef.value.replyData(id);
};

// 删除
const del = async (id) => {
  await delActivityInfoApi(id);
  ElMessage.success("删除成功");
  if (queryData.current > 1 && list.value.length === 1) queryData.current--;
  initData();
};

// 导出表格
const exportToExcel = () => {
  const key = Object.keys(list.value[0])
  const header = activeTable.map(item => item.label)// 表头信息
  const data = [header, ...list.value.map(item => [item.id, item.community.name, item.title, item.place, item.photo, item.sponsor_unit, item.status === 1 ? '有效' : '无效', formatTimes(item.begin_time), formatTimes(item.end_time), formatTimes(item.create_time), '操作'])]
  const ws = XLSX.utils.aoa_to_sheet(data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
  XLSX.writeFile(wb, '活动信息一览表.xlsx')
}
</script>
<template>
  <div>
    <div class="page-box">
      <div class="top">
        <span class="h_tit">活动管理</span>
        <span class="text">用于管理小区里不定期举办的各种任务</span>
      </div>

      <div class="utils">
        <el-form :model="queryData" label-width="80px" inline="true">
          <el-form-item label="小区名称" style="width: 200px">
            <el-select v-model="queryData.community_code" placeholder="请输入">
              <el-option v-for="item in getCommunityNameList" :key="item.id" :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="活动主题" style="width: 200px">
            <el-input v-model="queryData.title" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="状态" style="width: 200px">
            <el-select v-model="queryData.status" placeholder="请输入">
              <el-option v-for="item in statusText" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" style="width: 280px">
            <el-date-picker v-model="timeArr" @change="changeCreate" type="daterange" start-placeholder="请选择"
              end-placeholder="请选择" :default-value="[new Date(2010, 9, 1), new Date(2010, 10, 1)]" />
          </el-form-item>
          <el-form-item>
            <el-button @click="onReset">重置</el-button>
            <el-button @click="onSearch" type="primary">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <div class="table">
        <el-row type="flex" justify="space-between">
          <div></div>
          <div class="tab_utils">
            <el-button @click="exportToExcel" type="success" size="default">导出信息</el-button>
            <el-button :disabled="checkBtnAuth(77)" @click="addRef.isShow = true" type="primary"
              size="default">新增活动</el-button>
            <el-icon color="#409EFC" class="no-inherint"> </el-icon>
            <el-icon color="#409EFC" :icon="Share"> </el-icon>
            <el-icon color="#409EFC" class="no-inherint"> </el-icon>
          </div>
        </el-row>
        <br />
        <Table :table="activeTable" :tableData="list">
          <!-- 小区名称 -->
          <template #community.name="{ row }">
            {{ row.community?.name }}
          </template>
          <!-- 照片 -->
          <template #photo="{ row }">
            <div style="width: 100%">
              <ImagePreview :src="row.photo" alt="" :width="50" />
            </div>
          </template>
          <!-- 状态 -->
          <template #status="{ row }">
            {{ getStatusText(row.status) }}
          </template>
          <!-- 活动开始时间 -->
          <template #begin_time="{ row }">
            {{ formatTimes(row.begin_time) }}
          </template>
          <!-- 活动截止时间 -->
          <template #end_time="{ row }">
            {{ formatTimes(row.end_time) }}
          </template>
          <!-- 活动开始时间 -->
          <template #create_time="{ row }">
            {{ formatTimes(row.create_time) }}
          </template>
          <!-- 按钮权限 -->
          <template #operation="{ row }">
            <el-button type="text" @click="edit(row.id)" :disabled="checkBtnAuth(78)" v-loading.fullscreen.lock="isEdit"
              link>修改</el-button>
            <el-popconfirm title="是否确定删除" @confirm="del(row.id)">
              <template #reference>
                <el-button :disabled="checkBtnAuth(79)" type="text" link>删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </Table>
      </div>

      <!-- 分页区域 -->
      <Pagination v-model:pageNum="queryData.current" v-model:pageSize="queryData.pageSize" :total="total"
        @initData="initData" />

      <!-- 新增表单组件 -->
      <addForm ref="addRef" @updateList="initData" />
    </div>
  </div>
</template>
<style scoped>
.page-box {
  margin: 40px;
  min-height: 500px;
  background-color: #fbfbfc;
}

.h_tit {
  font-weight: 700;
  font-size: 18px;
}

.text {
  font-size: 15px;
  margin-left: 20px;
  color: #575858;
}

.top {
  margin: 10px;
}

.utils {
  margin-left: 5px;
  margin-right: 5px;
  padding: 20px;
  background-color: #fff;
  box-shadow: 5px 5px 5px 3px rgba(186, 177, 177, 0.2);
}

.table {
  margin: 5px;
  padding: 20px;
  margin-top: 10px;
  background-color: #fff;
  box-shadow: 5px 5px 5px 3px rgba(186, 177, 177, 0.2);
}
</style>
